<?php
namespace Addons\IcWaterGoods\Controller;
use Mp\Controller\MobileBaseController;
require_once(ADDON_PATH.'IcWaterGoods'.'/Common/Function.php');



/**
 * 水产圈移动端控制器
 * @author 16，陈浩南
 */
class MobileController extends MobileBaseController {
    private static $IMG_MAX_SIZE = 2097152;

	public function _initialize() {
//    session(null);
        parent::_initialize();
//          get_openid("ofCONv1WVGN2zjF-lOv-rF_nuTc8");	//设置一个测试openid
        $action = I('get.act');
        if($action != 'first' && $this->is_first()) redirect(create_mobile_url('first'));
    }

    //判断是否关注公众号
    public function isAuth(){
        $openid = get_openid();
        $is_subscribe = M('MpFans')->where(array('openid'=>$openid))->getField('is_subscribe');
        if($is_subscribe){
            $this->success('已关注');
        }else{
            $this->error('没有关注');
        }
    }
    public function test(){
        $this->display();
    }

    public function upload(){
        $mediaId = I('post.mediaId');
        $s = $this->uploadImg($mediaId);
        $this->ajaxReturn(array('status'=>1,'path'=>$s));
    }


    /*下载微信服务器图片*/
    public function uploadImg($mediaId){
        $imgDir   = './Uploads/Pictures';
        if(!is_dir($imgDir)){
            mkdir($imgDir);
        }
        $imgPath  = $imgDir.'/'.$mediaId.'.jpg';
        $wechatObj = get_wechat_obj();
         $str = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$wechatObj->checkAuth()."&media_id=".$mediaId.""; 
         $a = file_get_contents($str);  
         $resource = fopen($imgPath , 'w+');  
         fwrite($resource, $a);  
         //关闭资源  
         fclose($resource);  
         return $imgPath;
    }


    /*判断用户是否第一次进入页面*/
    private function is_first(){
        $model = D('Addons://IcWaterGoods/IcFollow');
        if(!$model->getOne(array('openid'=>get_openid()))){
            return true;
        }else{
            return false;
        }
    }

	/*首次进入*/
	public function first(){
	    /*如果已经关注了*/
        $model = D('Addons://IcWaterGoods/IcFollow');
        $url = create_mobile_url('index');

        if($model->getOne(array('openid'=>get_openid()))) redirect($url);
        if(IS_POST){
            $data['openid'] = get_openid();
            $data['tid'] = I('types');
            if(!$data['tid']) $this->error('请选择关注分类');

            if($model->addData($data)){
                $this->success('关注成功!',create_mobile_url('index'));
            }else{
                $this->error('关注失败');
            }
        }else{
            $openid = get_openid();
            $udata = get_fans_info($openid);
            $this->assign('uinfo',$udata);
            /*获取所有分类*/
            $typeModels = D('Addons://IcWaterGoods/IcGoodsTypes');
            $types = $typeModels->getTypesLists();
            $this->assign("types",$types);
            $this->display();
        }
	}

	public function index(){
	    /*获取配置*/
	    $config = get_addon_settings();
        $this->assign('config',$config);
        // 获取模型
        $model = D('Addons://IcWaterGoods/IcGoodsTypes');

        $typeList = $model->getTypesLists();



        $this->assign("infoDefaultType", "不限");
        $this->assign("goodsTypeList", $typeList);
        $this->assign("goodsDefaultType", "");
	    $this->display();
    }

    /*用户中心*/
    public function userCenter(){
        /*获取用户信息*/
        $data = get_fans_info(get_openid());
        $this->assign('info',$data);
        $this->display();
    }

    /*我的关注*/
    public function guanzhu(){
        $model = D('Addons://IcWaterGoods/IcFollow');
        if(IS_POST){

            $is_guan = I('post.is_guan');
            if(!$is_guan){
                $data['tid'] = -1;
            }else{
                $data['tid'] = I('post.types',-1);
            }
            if($model->update(array('openid'=>get_openid()),$data)){
                $this->success('关注设置成功!',create_mobile_url('userCenter'));
            }else{
                $this->error('选择失败!');
            }
        }else{

            $data = $model->getOne(array('openid'=>get_openid()));
            /*所有选中分类*/
            $types = $data['tid'] == -1 ? -1 : explode(',',$data['tid']);
            $this->assign('types',$types);
            /*获取所有分类*/
            $typeModels = D('Addons://IcWaterGoods/IcGoodsTypes');
            $typeLists = $typeModels->getTypesLists();
            $this->assign('typeList',$typeLists);

            $this->display();
        }

    }


    public function ajaxFabu($id = null) {
        /*获取配置*/
        $config = get_addon_settings();
        $this->assign('config',$config);

        // 检查是否超过一天最大发布数量
        $goodsModel = D('Addons://IcWaterGoods/IcGoods');
        if(!$goodsModel->canReleaseByMaxTimesLimit(get_openid(), $config['max_fabu'])) {
            $this->error("你今天的发布次数已经使用完毕");
            return;
        }




        // 获取变量
        $storeName = I("post.storeName");
        $phone = I("post.phone");
        $desc = I("post.desc");
        $cover = I("post.cover");

        $infoType = 0;
        if(I("post.infoType") == "求购信息") {
            $infoType = 1;
        }else if(I("post.infoType") == "货品信息"){
            $infoType = 2;
        }

        //需要认证
        if($config['need_auth'] == 1) {
            // 判断认证是否审核通过
            if($infoType == 2){
                $authModel = D('Addons://IcWaterGoods/IcAuthentication');
                $auth = $authModel->getAuth(get_openid());
                if($auth == null || $auth['status'] != 2) {
                    $ajax['status'] = 0;
                    $ajax['info'] = '验证通过后才能使用该功能';
                    $ajax['url'] = create_mobile_url('auth');
                    $this->ajaxReturn($ajax);
                    return;
                }
            }
        }

        $goodsType = I("post.goodsType");
        $typeModel = D('Addons://IcWaterGoods/IcGoodsTypes');
        $goodsType = $typeModel->getTypeIdByStr($goodsType);


        // 检测
        // 描述最多500字
        if(strlen($desc) > 500) {
            $this->error("描述最多只能输入500字");
        }
        // 图片最多9张
        if (count($cover) > 9) {
            $this->error("最多只能上传9张图片");
        }

        // 店名不能为空
        if ($storeName == '') {
            $this->error("请填写店名");
        }
        // 电话不能为空
        if($phone == '') {
            $this->error("请填写手机号码");
        }

        //分类不能为空
        if(!$goodsType){
            $this->error("货品分类不能为空");
        }


        // 保存图片
        // 定义变量
        $localRoot = substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'], "/")) . "/Uploads";
        $urlRoot = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/"));
        $urlRoot = $urlRoot . "/Uploads";



        // 写入数据库
        $dbData['info_type'] = $infoType;
        $dbData['good_type'] = $goodsType;
        $dbData['describe'] = $desc;
        $dbData['openid'] = get_openid();
        $dbData['status'] = 1;
        $dbData['shop_name'] = $storeName;
        $dbData['mobile'] = $phone;
        $dbData['imgs'] = json_encode($cover);





        if($id === null) {
            $id = $goodsModel->addData($dbData);
            if($id) {
                /*查看关注用户*/
                $model = D('Addons://IcWaterGoods/IcFollow');
                $where =  'tid like "%'.$goodsType.',%" or tid like "'.$goodsType.',%"';
                $userData = $model->where($where)->getField('openid',true);
                $arr = array(
                    "template_id"=>"D4thuhB44AWUzoP-GcV9IegoCeCycbm41BafOHGY3F8",
                    "url"=>create_mobile_url('detail',array('id'=>$id)),
                    "topcolor"=>"#FF0000",
                    "data"=>array(
                    )
                );
                sendTemp($userData,$arr);
                $this->success("发布成功", create_mobile_url("index"));
            }else {
                $this->error("发布失败");
            }
        }else {
            if($goodsModel->where(array('id'=>$id))->save($dbData)) {
                $this->success("保存成功");
            }else {
                $this->error("请修改信息");
            }
        }



    }

    /*发布页面*/
    public function fabu($id = null) {
        $type = I('get.type','货品信息');
        $config = get_addon_settings();
        $typeModel = D('Addons://IcWaterGoods/IcGoodsTypes');
        if($type == '求购信息'){
            //求购
            $typeList = $typeModel->getTypesLists();
            $this->assign("goodsTypeList", $typeList);
        }else {
            //货品

            //需要认证
            if ($config['need_auth'] == 1) {
                // 判断认证是否审核通过
                $authModel = D('Addons://IcWaterGoods/IcAuthentication');
                $auth = $authModel->getAuth(get_openid());
                $data['shop_name'] = $auth['shop_name'];
                $data['mobile'] = $auth['mobile'];
                $this->assign('data', $data);
            }

            /*是否需要关注公众号*/
            if ($config['is_guan']) {
                if (!M('MpFans')->where(array('openid' => get_openid()))->getField('is_subscribe')) {
                    redirect(create_mobile_url('code'));
                }
            }
            /*获取用户权限*/
            $typeList = $typeModel->getUserTypesLists();
            $this->assign("goodsTypeList", $typeList);
        }

        $this->assign("infoType",$type);

        if ($id === null) {
            // 获取模型
//            $this->assign("infoType", "求购信息");
            $this->assign("goodsType", $typeModel->getFirstType($typeList));
        }else {
            $goodsModel = D('Addons://IcWaterGoods/IcGoods');
            $data = $goodsModel->getOne(array('id'=>$id));


            if($data['info_type'] == 1) {
                 $data['info_type'] = "求购信息";
            }else if($data['info_type'] == 2) {
                 $data['info_type'] = "货品信息";
            }

            $data['good_type'] = $typeModel->getTypeStrById($data['good_type']);
            $data['imgs'] = json_decode($data['imgs'], true);
            $this->assign("infoType", $data['info_type']);
            $this->assign("goodsType", $data['good_type']);
            $this->assign("data", $data);
        }
        $this->display();
    }


    public function getGoods($page, $size) {
        $model = D('Addons://IcWaterGoods/IcGoods');
//        dump($model->getGoodsList($page, $size));
    }

    public function ajaxRemoveGoods($id) {
        $model = D('Addons://IcWaterGoods/IcGoods');
        $model->remove($id);
    }

    /*
    dataArray = [
        {
            id: 1,
            head: "img/touxiang.jpg" ,
            username: "我就是大佬" ,
            desc: "weui目前是比较好用2222222222的ui,在微信和手机中表现非常好。",
            imgs: [
                "img/418.jpg",
                "img/418.jpg",
                "img/418.jpg"
            ],
            date: "09-07 00:52",
            comment: [
                {
                    username: "Yoby",
                    content: "巴拉巴拉"
                },
                {
                    username: "热狗",
                    receiver: "Yoby",
                    content: "热狗好热"
                }
            ]
        }
    ];
    */
    public function ajaxGetGoods($infoType, $goodsType, $page, $size) {
//    public function ajaxGetGoods() {
        /*dump($_GET);
        exit();*/
        $msgModel = D('Addons://IcWaterGoods/IcMessage');
        $typeModel = D('Addons://IcWaterGoods/IcGoodsTypes');
        $model = D('Addons://IcWaterGoods/IcGoods');
        if($infoType == "求购信息") {
            $infoType = 1;
        }else if($infoType == "货品信息") {
            $infoType = 2;
        }else {
            $infoType = 2;
        }
        $goodsType = $typeModel->getTypeIdByStr($goodsType);
        $goodsList = $model->getGoodsList($infoType, $goodsType, $page, $size);
//        $goodsList = $model->getGoodsList($page, $size);

        $goodsListData = array();
        foreach($goodsList as $goods) {
            // 图片
            $imgs = json_decode($goods['imgs']);
            /*foreach(json_decode($goods['imgs'], true) as $img) {
                // $img = json_decode($img);
                array_push($imgs, $img['url']);
            }*/
            // 评论
            $comments = array();
            $mesData = $msgModel->getGoods($goods['id']);
            $num = count($mesData);
            $username = array();
            $ps = array();
            for($i=0;$i<$num;$i++){
                $mesData[$i]['nickname'] = $username[$mesData[$i]['id']] = get_fans_nickname($mesData[$i]['reply_openid']);
                if ($mesData[$i]['pid'] == 0) {
                    $comments[$mesData[$i]['id']] = $mesData[$i];
                    $ps[$mesData[$i]['id']] = $mesData[$i]['id'];
                } else {
                    $a = $ps[$mesData[$i]['pid']];
                    $mesData[$i]['rele'] =$username[$mesData[$i]['pid']];
                    $comments[$a]['c'][] = $mesData[$i];
                    $ps[$mesData[$i]['id']] = $a;
                }
            }
//            foreach ($mesData as $msg) {
//                $msg['nickname'] = get_fans_nickname($msg['reply_openid']);
//                if ($msg['pid'] == 0) {
//                    $comments[$msg['id']] = $msg;
//                } else {
//                    $msg['rele'] = get_fans_nickname($mesData[$msg['pid']]['reply_openid']);
//                    $comments[$msg['pid']]['c'][] = $msg;
//                }
//            }
            // 整体信息
            $goodsData = array(
                 'id' => $goods['id'] ,
                'mobile'=>$goods['mobile'],
                'head' => get_fans_info($goods['openid'], 'headimgurl') ,
                'username' => get_fans_nickname($goods['openid']) ,
                'desc' => $goods['describe'] ,
                'imgs' => $imgs ,
                'date' => date("m-d H:i", $goods['create_time']) ,
                'comment'=>array_values($comments)
            );
            array_push($goodsListData, $goodsData);
        }

        $this->ajaxReturn($goodsListData);
    }

    /*我的发布*/
    public function myfabu() {
        // 获取信息
        $person['nickname'] = get_fans_nickname(get_openid());
        $person['headimgurl'] = get_fans_info(get_openid(), 'headimgurl');
        $this->assign("person", $person);

        // 获取货品列表
        $model = D('Addons://IcWaterGoods/IcGoods');
        $goodsList = $model->getListAll('', array('openid'=>get_openid()), false, 'create_time desc');
        foreach($goodsList as &$goods) {
            $goods['year'] = date("y", $goods['create_time']);
            $goods['month'] = date("m", $goods['create_time']);
            $goods['imgs'] = json_decode($goods['imgs'], true);
        }
        $this->assign("goodsList", $goodsList);


        $this->display();
    }
    

    /*详情*/
    public function myDetail(){
        $config = get_addon_settings();
        $this->assign('config',$config);
        $id = I('get.id');
        $openid = M('IcGoods')->where(array('id'=>$id))->getField('openid');
//        $openid = get_openid()
        $model = D('Addons://IcWaterGoods/IcGoods');
        $data = $model->getListAll('',array('openid'=>$openid));

        $num = count($data);
        for($i=0;$i<$num;$i++){

            $data[$i]['imgs'] = json_decode($data[$i]['imgs']);
            $arr = array();
           
            foreach($data[$i]['imgs'] as $val){
                array_push($arr, $val);
            }
            $data[$i]['imgs'] = $arr;
        }

       

        $this->assign('data',$data);
        $this->assign('info',get_fans_info($openid));
        $this->display();
    }

    public function detail(){
        $id = I('get.id',0,'intval');
        $model = D('Addons://IcWaterGoods/IcGoods');
        $data = $model->getOne(array('id'=>$id));
        $data['imgs'] = json_decode($data['imgs']);
        $arr = array();
        foreach($data['imgs'] as $val){
            array_push($arr, $val);
        }
        $data['imgs'] = $arr;
        $this->assign('info',get_fans_info($data['openid']));
        $this->assign('data',$data);

        /*获取所有留言*/
        $num = M('IcMessage')->where(array('gid'=>$data['id']))->count();
        $this->assign('num',$num);
        $comments = array();
        $model = D('Addons://IcWaterGoods/IcMessage');
        $mesData = $model->getGoods($data['id']);
        $num = count($mesData);
        $username = array();
        $ps = array();
        for($i=0;$i<$num;$i++){
            $info = get_fans_info($mesData[$i]['reply_openid']);
            $mesData[$i]['username'] = $username[$mesData[$i]['id']] = $info['nickname'];
            $mesData[$i]['headimgurl'] =  $info['headimgurl'];
            if ($mesData[$i]['pid'] == 0) {
                $comments[$mesData[$i]['id']] = $mesData[$i];
                $ps[$mesData[$i]['id']] = $mesData[$i]['id'];
            } else {
                $mesData[$i]['rele'] =$username[$mesData[$i]['pid']];
                $a = $ps[$mesData[$i]['pid']];
                $comments[$a]['c'][] = $mesData[$i];
                $ps[$mesData[$i]['id']] = $a;
            }
        }
        $this->assign('comments',$comments);
        $this->display();
    }
    /*发送评论*/
    public function setmessage(){
        $data['reply_openid'] = get_openid();
        $data['pid'] = I('post.pid',0);
        $data["mpid"] = get_mpid();
        $data["gid"] = I('post.gid');
        $data["create_time"] = time();
        $data["status"] = 1;
        $data["content"] = I('post.content');
        if($id = M('IcMessage')->add($data)){
            $ajax['info'] = '发布成功';
            $ajax['status'] = 1;
            $info = get_fans_info(get_openid());
            $ajax['mess']['nickname'] = $info['nickname'];
            $ajax['mess']['headimgurl'] = $info['headimgurl'];
            $ajax['mess']['id'] = $id;
            if($data['pid']){
                $next = M('IcMessage')->where(array('id'=>$data['pid']))->getField('reply_openid');
                $ajax['mess']['repeNickname'] = get_fans_nickname($next);
            }
            /*发送模板提醒用户*/
            $arr = array(
                "template_id"=>"PkMFVJgWgwXTWeMzkueHibxbyQ2cvAxnaSDFQGf8FlY",
                "url"=>create_mobile_url('detail',array('id'=>$data['gid'])),
                "topcolor"=>"#FF0000",
                "data"=>array(
                    'value1'=>array(
                        'value'=>$info['nickname'],
                        "color"=>"#173177"
                    ),
                    'value2'=>array(
                        'value'=>$data["content"],
                        "color"=>"#173177"
                    ),
                    'value3'=>array(
                        'value'=>date('m-d H:i',time()),
                        "color"=>"#173177"
                    ),
                )
            );
            $repe = $next ? $next : M('IcGoods')->where(array('id'=>$data['gid']))->getField('openid');
            sendTemp($repe,$arr);
            $this->ajaxReturn($ajax);
        }else{
            $this->error("发布失败");
        }
    }

    public function code(){
        if(M('MpFans')->where(array('openid'=>get_openid()))->getField('is_subscribe')) redirect(create_mobile_url('index'));
        $config = get_addon_settings();
        $this->assign('img',$config['guan_imgs']);
        $this->display();
    }

    private function saveImg($data, $maxSize, &$getError) {
        // 定义变量
        $localRoot = substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'], "/")) . "/Uploads";
        $urlRoot = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/"));
        $urlRoot = $urlRoot . "/Uploads";


        $head = substr($data, 0, 100);
        preg_match("/data:image\/(.*);base64,/", $head, $res);
        $ext = $res[1];
        $head = preg_replace("/data:image\/(.*);base64,/", "", $head);
        $tail = substr($data, 100);
        $data = $head . $tail;
        $data = base64_decode($data);



        if($data == false) {
            $getError = "上传出错";
            return false;
        }

        if(strlen($data) > $maxSize) {
            $getError = "图片过大";
            return false;
        }

        $filename = get_file_name() . '.' . $ext;
        if(file_put_contents($localRoot . '/' . $filename, $data)) {
            $img['local'] = $localRoot . '/' . $filename;
            $img['url'] = $urlRoot . '/' . $filename;
            $img['ext'] = $ext;
        }else {
            $getError = "上传出错";
            return false;
        }

        return json_encode($img);
//        return $img['url'];
    }

    public function ajaxAuth($shopName, $mobile, $img1, $img2) {
        // 如果正在审核或者通过了审核，则将之前的审核删除
        $model = D('Addons://IcWaterGoods/IcAuthentication');
        $model->where(array('openid'=>get_openid()))->delete();

        $data['shop_name'] = $shopName;
        $data['mobile'] = $mobile;
        $data['img1'] = $img1;
        $data['img2'] = $img2;
        $data['openid'] = get_openid();
        $data['status'] = 1;


        if($model->addData($data)) {
            $this->success("提交审核成功", create_mobile_url("auth"));
        }else {
            $this->error("提交审核失败");
        }
    }

    public function auth() {
        $authModel = D('Addons://IcWaterGoods/IcAuthentication');
        $auth = $authModel->getAuth(get_openid());
        if($auth) {
            /*if($auth['status'] == 1) {
                // 正在审核
            }else if($auth['status'] == 2) {
                // 审核通过
            }*/



            $this->assign("img1", $auth['img1']);
            $this->assign("img2", $auth['img2']);
            $this->assign("shopName", $auth['shop_name']);
            $this->assign("mobile", $auth['mobile']);

            $this->assign("status", $auth['status']);
        }else {
            $this->assign("status", 0);
        }

        $this->display();
    }
}